<template>
  <div id="app">
    <h2>创建订单</h2>
    <label for="product-info">商品信息:</label>
    <input v-model="productInfo" type="text" id="product-info" placeholder="请输入商品信息">
    <label for="totalAmount">订单金额:</label>
    <input v-model="totalAmount" type="number" id="totalAmount" placeholder="请输入订单金额">
    <button @click="createOrder">创建订单</button>

    <h2>订单列表</h2>
    <table>
      <thead>
        <tr>
          <th>订单 ID</th>
          <th>商品名称</th>
          <th>订单状态</th>
          <th>总价</th>
          <th>用户 ID</th>
          <th>支付方式</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-if="orderList.length > 0" v-for="order in orderList" :key="order.orderId">
          <td>{{ order.orderId }}</td>
          <td>{{ order.subjectName }}</td>
          <td>{{ order.orderStatus }}</td>
          <td>{{ order.totalAmount }}</td>
          <td>{{ order.userId }}</td>
          <td>
            <select 
              v-model="paymentMethods[order.orderId]"
              :disabled="!canChangePayment(order)"
              class="payment-select"
            >
              <option value="alipay">支付宝</option>
              <option value="unionPay">银联支付</option>
            </select>
          </td>
          <td>
            <button 
              @click="initiatePayment(order)"
              :disabled="!canPay(order)"
              :class="{ 'disabled-button': !canPay(order) }"
            >
            {{ paymentButtonText(order) }}
            </button>
            <button 
              @click="cancelOrder(order)"
              :disabled="!canCancel(order)"
              :class="{ 'disabled-button': !canCancel(order) }"
            >
              取消订单
            </button>
          </td>
        </tr>
        <tr v-else>
          <td colspan="6">暂无订单</td>
        </tr>
      </tbody>
    </table>

    <div v-if="paymentInfo">
      <h2>支付信息</h2>
      <p>{{ paymentInfo.message }}</p>
    </div>

    <h2>获取支付结果</h2>
    <label for="order-id">订单 ID:</label>
    <input v-model="orderId" type="text" id="order-id" placeholder="请输入订单 ID">
    <button @click="getPaymentResult">获取支付结果</button>
  </div>

    <!-- 添加取消订单的模态对话框 -->
    <div v-if="showCancelModal" class="modal">
      <div class="modal-content">
        <h3>取消订单</h3>
        <p>请输入取消原因:</p>
        <textarea v-model="cancelReason" placeholder="请输入取消原因..."></textarea>
        <div class="modal-actions">
          <button @click="confirmCancel">提交</button>
          <button @click="closeModal">取消</button>
        </div>
        <p v-if="showError" class="error-message">请输入取消原因</p>
      </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

// 表单数据
const productInfo = ref('');
const totalAmount = ref('');
const orderId = ref('');
const queryOrderId = ref('');
const expand = ref('');
const showCancelModal = ref(false);
const cancelReason = ref('');
const showError = ref(false);
const currentOrder = ref(null);

// 新增响应式数据
const paymentMethods = ref({});
const defaultPaymentMethod = ref('alipay');

// 新增方法
const paymentButtonText = (order) => {
  const method = paymentMethods.value[order.orderId];
  return method === 'alipay' ? '支付宝支付' : '银联支付';
};

const canChangePayment = (order) => {
  return ['unpaid', 'paying'].includes(order.orderStatus?.toLowerCase());
};


// 订单列表和支付信息
const orderList = ref([]);
const paymentInfo = ref(null);

// 获取环境变量中的 API 基础 URL
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;

// 创建订单
const createOrder = async () => {
  try {
    const response = await fetch(`${apiBaseUrl}/order/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        totalAmount: parseFloat(totalAmount.value),
        subjectName: productInfo.value,
        userId: "jiajin"
      })
    });
    const data = await response.json();
    queryOrderList();
  } catch (error) {
    console.error('创建订单出错:', error);
  }
};

// 在查询订单列表时初始化支付方式
const queryOrderList = async () => {
  try {
    const url = new URL(`${apiBaseUrl}/order/list`);
    url.searchParams.append('userId', "jiajin");

    const response = await fetch(url);
    const result = await response.json();
    if (result.code === 200) {
      orderList.value = result.data;
      // 初始化支付方式
      result.data.forEach(order => {
        if (!paymentMethods.value[order.orderId]) {
          paymentMethods.value[order.orderId] = defaultPaymentMethod.value;
        }
      });
    }
  } catch (error) {
    console.error('查询订单列表出错:', error);
  }
};

// 取消订单
const cancelOrder = async (order) => {
  currentOrder.value = order;
  showCancelModal.value = true;
  cancelReason.value = '';
  showError.value = false;
};

// 关闭模态框
const closeModal = () => {
  showCancelModal.value = false;
};

// 确认取消订单
const confirmCancel = async () => {
  if (!cancelReason.value.trim()) {
    showError.value = true;
    return;
  }
  
  try {
    const response = await fetch(`${apiBaseUrl}/payment/cancel`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        orderId: currentOrder.value.orderId,
        reason: cancelReason.value
      })
    });
    const data = await response.json();
    queryOrderList();
    closeModal();
  } catch (error) {
    console.error('取消订单出错:', error);
  }
};

// 发起支付
const initiatePayment = async (order) => {
  try {
    const paymentResponse = await sendPaymentRequest(order);
    if (paymentResponse.code === 200) {
      const formHtml = paymentResponse.data;
      const form = parseHtmlForm(formHtml);
      if (form) {
        submitForm(form);
      } else {
        console.error('支付表单解析失败');
      }
    } else {
      paymentInfo.value = { message: paymentResponse.message };
    }
  } catch (error) {
    console.error('发起支付出错:', error);
  }
};

// 判断是否可以支付的方法
const canPay = (order) => {
  return ['unpaid', 'paying'].includes(order.orderStatus?.toLowerCase());
};

// 新增判断是否可以取消的方法
const canCancel = (order) => {
  return ['unpaid', 'paying'].includes(order.orderStatus?.toLowerCase());
};


// 修改后的支付请求方法
const sendPaymentRequest = async (order) => {
  const paymentMethod = paymentMethods.value[order.orderId] || defaultPaymentMethod.value;
  
  const response = await fetch(`${apiBaseUrl}/payment/initiate`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      orderId: order.orderId,
      totalAmount: order.totalAmount,
      subjectName: order.subjectName,
      paymentMethod: paymentMethod  // 添加支付方式参数
    })
  });
  return await response.json();
};

// 解析 HTML 表单
const parseHtmlForm = (formHtml) => {
  const formDoc = new DOMParser().parseFromString(formHtml, 'text/html');
  return formDoc.querySelector('form');
};

// 创建并提交表单
const submitForm = (form) => {
  const tempForm = document.createElement('form');
  tempForm.method = form.method || 'POST';
  tempForm.action = form.action || '';

  const inputs = form.querySelectorAll('input');
  inputs.forEach(input => {
    if (input.name && input.value) {
      const newInput = document.createElement('input');
      newInput.type = input.type || 'hidden';
      newInput.name = input.name;
      newInput.value = input.value;
      tempForm.appendChild(newInput);
    }
  });

  document.body.appendChild(tempForm);
  tempForm.submit();
  document.body.removeChild(tempForm);
};


// 获取支付结果
const getPaymentResult = async () => {
  try {
    const response = await fetch(`${apiBaseUrl}/get-payment-result?orderId=${orderId.value}`);
    const data = await response.json();
    paymentInfo.value = { message: `支付结果: ${data.status}` };
  } catch (error) {
    console.error('获取支付结果出错:', error);
  }
};

// 页面加载时自动查询订单列表
onMounted(() => {
  queryOrderList();
});
</script>

<style scoped>
body {
  font-family: Arial, sans-serif;
  padding: 20px;
}

h2 {
  margin-bottom: 10px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input[type="text"],
input[type="number"] {
  width: 100%;
  padding: 8px;
  margin-bottom: 15px;
  box-sizing: border-box;
}

button {
  padding: 10px 20px;
  background-color: #007BFF;
  color: white;
  border: none;
  cursor: pointer;
  margin-right: 10px;
}

button:hover {
  background-color: #0056b3;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th,
td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: left;
}

th {
  background-color: #f0f0f0;
}

/* 新增模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 400px;
  max-width: 90%;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 10px;
}

.modal-actions button {
  padding: 8px 16px;
}

textarea {
  width: 100%;
  height: 100px;
  padding: 8px;
  box-sizing: border-box;
  margin-top: 10px;
  resize: vertical;
}

.error-message {
  color: red;
  margin-top: 10px;
}

/* 禁用按钮的样式 */
button:disabled,
.disabled-button {
  background-color: #cccccc !important;
  cursor: not-allowed !important;
  opacity: 0.6;
}

button:disabled:hover,
.disabled-button:hover {
  background-color: #cccccc !important;
}

.payment-select {
  padding: 5px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-right: 10px;
}

.disabled-select {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
</style>